const api = require('../../api/api.js');
const util = require('../../utils/util.js');
const app = getApp();

Page({
  data: {
    isNew: true, //判断此次提交时更新表还是添加数据
    place: {},
    isDisabled: true,
    images: [],
    images_copy: [],
    imgUrl: app.globalData.imgUrl + 'placeImage/',
    tip: '',
    icon: '/imgs/icon_edit.png',
    delImgs: [],
    addImgs: [],
    index: 0,
    index_copy: -1
  },
  onLoad(o) {
    let that = this;
    let placeId = o.placeId;
    that.queryClaim(placeId);
    that.queryGood();
    that.queryPlaceImage(placeId);
    that.queryPlaceInfo(placeId);
    that.setData({
      placeId
    });
  },
  queryPlaceInfo(placeId) {
    let that = this;
    api.queryPlaceInfo({
      data: {
        placeId,
        userId: ''
      },
      success(res) {
        if (res.data.placeInfos.length === 0) {
          that.queryPlaces(placeId);
        } else {
          let pi = res.data.placeInfos[0];
          let place = that.data.place;
          place.placeName = pi.name;
          place.produce = pi.produce;
          place.good = pi.good;
          place.remark = pi.remark;
          that.setData({
            place,
            isNew: false
          });
        }
      }
    });
  },
  queryClaim(placeId) {
    let that = this;
    placeId = Number.parseInt(placeId);
    api.queryClaim({
      data: {
        placeId,
        userId: ''
      },
      success(res) {
        console.log(res.data);
        let claimant = '';
        if (res.data.claims.length === 0) {
          claimant = '此地块暂时未被认领！';
        } else {
          claimant = res.data.claims[0].account;
        }
        let place = that.data.place;
        place.claimant = claimant;
        that.setData({
          place
        });
      }
    });
  },
  queryGood() {
    let that = this;
    wx.getStorage({
      key: 'userId',
      success(res) {
        let userId = res.data;
        api.queryGood({
          data: {
            id: -1,
            userId
          },
          success(res) {
            console.log(res.data);
            let goods = res.data.good;

            let goodName = goods.map((i) => {
              return i.name;
            });
            goodName.push('未选择');

            let goodId = goods.map((i) => {
              return i.id;
            });
            goodId.push(-1);

            let good = that.data.place.good;
            let index = goodName.length - 1;
            if (good !== undefined) {
              for (let i = 0; i < goodId.length; i++) {
                if (good === goodId[i]) {
                  index = i;
                  break;
                }
              }
            }
            that.setData({
              goodName,
              goodId,
              index
            });
          }
        });
      }
    });
  },
  queryPlaceImage(placeId) {
    let that = this;
    api.queryPlaceImage({
      data: {
        placeId
      },
      success(res) {
        console.log(res.data);
        let images = res.data.placeImages;
        let imgUrl = that.data.imgUrl;
        let tip = '';
        images = images.map((i) => {
          return {
            imgUrl: imgUrl + i.imgUrl,
            imgID: i.imgId
          }
        });
        if (images.length === 9) {
          tip = '(最多九张)';
        }
        that.setData({
          tip,
          images
        });
      }
    });
  },
  queryPlaces(placeId) {
    let that = this;
    api.queryPlaces({
      data: {
        placeId,
        siteId: -1,
        limit: -1,
        pageNumber: 0,
        type: ''
      },
      success(res) {
        console.log(res.data);
        let p = res.data.places[0];
        let place = that.data.place;
        place.placeName = p.placeName;
        place.produce = p.crop;
        place.remark = '暂无简介！';
        that.setData({
          place
        });
      }
    });
  },
  edit() {
    let that = this;
    let isDisabled = !that.data.isDisabled;
    let icon;
    let tip = '';
    if (isDisabled === true) {
      wx.showModal({
        title: '提示',
        content: '取消编辑？',
        success(res) {
          if (res.confirm) {
            icon = '/imgs/icon_edit.png';
            if (that.data.images_copy.length === 9) {
              tip = '(最多九张)';
            }
            that.setData({
              tip: tip,
              place: that.data.place_copy,
              index: that.data.index_copy,
              images: that.data.images_copy.concat(),
              isDisabled: isDisabled,
              icon: icon
            });
          }
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '编辑资料？',
        success(res) {
          if (res.confirm) {
            icon = '/imgs/icon_cancel.png';
            that.setData({
              place_copy: that.data.place,
              index_copy: that.data.index,
              images_copy: that.data.images.concat(),
              isDisabled: isDisabled,
              icon: icon
            });
          }
        }
      })
    }
  },
  delimg(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let images = this.data.images;
    let addImgs = this.data.addImgs;
    let img = images[index];
    wx.showModal({
      title: '提示',
      content: '确定删除吗？',
      success(e) {
        if (e.confirm) {
          images.splice(index, 1);
          if (img.imgID === -1) {
            for (let i = 0; i < addImgs.length; i++) {
              if (img.imgUrl === addImgs[i]) {
                addImgs.splice(i, 1);
              }
            }
          } else {
            that.data.delImgs.push(img.imgID);
          }
          that.setData({
            images: images,
            tip: ''
          });
        }
      }
    })
  },
  addimg() {
    let that = this;
    let images = this.data.images;
    let tip = '';
    wx.chooseImage({
      count: 9 - images.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        let tempFilePaths = res.tempFilePaths;
        that.data.addImgs.push(...tempFilePaths);
        tempFilePaths = tempFilePaths.map((i) => {
          return {
            imgUrl: i,
            imgID: -1
          }
        });
        images.push(...tempFilePaths);
        if (images.length === 9) {
          tip = '(最多九张)';
        }
        that.setData({
          images: images,
          tip: tip
        });
      }
    })
  },
  delImage(count) {
    let that = this;
    let imgs = this.data.delImgs;
    let len = imgs.length;
    let id = imgs[count];
    if (count === len) {
      return;
    }
    api.delPlaceImage({
      data: {
        imgId: id
      },
      success(res) {
        that.delImage(++count);
      }
    });
  },
  addImage(count) {
    let that = this;
    let imgs = this.data.addImgs;
    let len = imgs.length;
    let img = imgs[count];
    let placeId = this.data.placeId;
    if (count === len) {
      return;
    }
    wx.getStorage({
      key: 'userId',
      success(res) {
        let userId = res.data;
        api.addFile({
          data: {
            userId: userId,
            path: 'placeImage',
            filePath: img
          },
          success(res) {
            let image = JSON.parse(res.data).fileName;
            api.addPlaceImage({
              data: {
                imgUrl: image,
                placeId
              },
              success(res) {
                that.addImage(++count);
              }
            });
          }
        });
      }
    })
  },
  formSubmit(e) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定修改吗？',
      success(res) {
        if (res.confirm) {
          let placeId = that.data.placeId;
          let name = e.detail.value.name.trim();
          // let produce = e.detail.value.produce.trim();
          // let good = that.data.goodId[that.data.index];
          let remark = e.detail.value.remark.trim();
          if (name === '' || remark === '') {
            wx.showToast({
              title: '请将内容填写完整！',
              icon: 'none'
            })
            return;
          }
          // if (good === -1) {
          //   wx.showToast({
          //     title: '请选择商品！',
          //     icon: 'none'
          //   })
          //   return;
          // }
          that.updatePlace(placeId, name, '');// ''为produce
          let params = {
            data: {
              placeId,
              name,
              produce: '',
              good: 1,
              remark,
              isClaimed: ''
            },
            success(res) {
              that.final();
            }
          };
          if (that.data.isNew) {
            api.addPlaceInfo(params);
          } else {
            api.updatePlaceInfo(params);
          }
        }
      }
    })
  },
  updatePlace(placeId, placeName, produce) {
    api.updatePlace({
      data: {
        placeId,
        placeName,
        produce
      }
    });
  },
  final() {
    wx.showToast({
      title: '修改成功！',
      icon: 'none'
    });
    this.addImage(0);
    this.delImage(0);
    let pages = getCurrentPages();
    pages[pages.length - 2].onLoad();
    wx.navigateBack({
      delta: -1
    });
  },
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
})